const http = require('http');
const express = require('express');
const static = require('express-static');
const consolidate = require('consolidate');
const io = require('socket.io');
const common = require('./lib/common');
//http服务
var app = express();
var server = http.createServer(app);
server.listen(8080);
// app.listen(8080);

//ws服务
var allSocket = [];
const oSocket = io.listen(server);
oSocket.on('connection', function (socket) {
    allSocket.push(socket);
    console.log( `当前连接数:${allSocket.length}` );
    var current_user_id = 0;
    var current_user_name = '';
    socket.on('reg', function (username, password) {
        //查询账号是否重复
        common.db().query(`select * from user_table where user_name='${username}'`, (err, data) => {
            if (err) {
                socket.emit('reg_ret', 1, '注册失败');
            } else {
                if (data.length > 0) {
                    socket.emit('reg_ret', 1, '账号重复');
                } else {
                    common.db().query(`INSERT INTO user_table(user_name,user_pass,online) VALUES('${username}','${password}',0)`, function (err) {
                        if (err) {
                            console.log(err);
                            socket.emit('reg_ret', 1, '注册失败');
                        } else {
                            socket.emit('reg_ret', 0, '注册成功');
                        }
                    });
                }
            }
        });
    });

    //登录
    socket.on('login', (username, password) => {

        common.db().query(`select * from user_table where user_name='${username}'`, (err, data) => {
            if (err) {
                socket.emit('login_ret', 1, '登录失败');
            } else {
                if (data.length == 0) {
                    socket.emit('login_ret', 1, '账号错误');
                } else {
                    if (data[0]['user_pass'] != password) {
                        socket.emit('login_ret', 1, '密码有误');
                    } else {
                        //设置在线状态为 上线
                        common.db().query(`update user_table set online=1 where id='${data[0].id}'`, err => {
                            if (err) {
                                socket.emit('login_ret', 1, '登录失败');
                            } else {
                                //保存当前用户
                                current_user_id = data[0].id;
                                current_user_name = data[0].user_name;
                                //统计在线人数
                                common.db().query('select count(*) as num from user_table where online=1', (err, data) => {
                                    if (err) {
                                        console.log(err);
                                        oSocket.emit('count_ret', '网络异常');
                                    } else {
                                        oSocket.emit('count_ret', data[0].num);
                                        socket.emit('login_ret', 0, '登录成功');
                                    }
                                });
                            }
                        });
                    }
                }
            }
        });

    });

    socket.on('count', function () {
        //统计在线人数
        common.db().query('select count(*) as num from user_table where online=1', (err, data) => {
            if (err) {
                console.log(err);
                /* socket.broadcast.emit('count_ret', '网络异常'); */
                socket.emit( 'count_ret', '网络异常' );
            } else {
                /* socket.broadcast.emit('count_ret', data[0].num); */
                oSocket.emit( 'count_ret', data[0].num );
            }
        });
    });

    //发消息
    socket.on('msg', text => {
        if (!current_user_id) {
            socket.emit('login_ret', 1, '请先登录...');
            return;
        }
        /* socket.broadcast.emit( 'broadcast','大家好' ); */  //使用广播

        if (!text) {
            socket.emit('msg_ret', 1, '消息文本不能为空');
        } else {
            //广播给所有的人
            allSocket.forEach(item => {
                if (item == socket) return;
                item.emit('msg', current_user_name, text);
            });
            socket.emit('msg_ret', 0, '发送成功');
        }
    });

    //离线
    socket.on('disconnect', function () {
        console.log('离线');
        common.db().query(`update user_table set online = 0  where id=${current_user_id}`, err => {
            if (err) {
                console.log('数据库错误');
            }
            current_user_id = 0;
            current_user_name = '';

            //统计在线人数
            common.db().query('select count(*) as num from user_table where online=1', (err, data) => {
                if (err) {
                    console.log(err);
                    socket.emit('count_ret', '网络异常');
                } else {
                    oSocket.emit('count_ret', data[0].num);
                }
            });

            allSocket = allSocket.filter(item => item != socket);
        });
    });
});



app.set('view engine', 'html');
app.set('views', './template');
app.engine('html', consolidate.ejs);


//根目录请求转移到前台
app.use('/', require('./route/index'));
app.use(static('./www'));
